package org.scboy.rbac.service.imp;

import java.util.Date;
import java.util.List;

import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.rbac.dao.RbacOrgRoleDao;
import org.scboy.rbac.dao.RbacUserRoleDao;
import org.scboy.rbac.service.OrgRoleService;
import org.scboy.utils.entitys.coobi.Model;
import org.scboy.utils.entitys.coobi.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.core.lang.UUID;

@Service
public class OrgRoleServiceImp implements OrgRoleService {


	@Autowired
	EntityFactory factory;
	
	@Override
	public Page page(Model params) {
		RbacOrgRoleDao dao=factory.getDao(RbacOrgRoleDao.class);
		RbacUserRoleDao roleDao=factory.getDao(RbacUserRoleDao.class);
		Page page=dao.queryPage(params);
		for (Model data : page.getData()) {
			long count=roleDao.count(Model.create().add("orId", data.getString("id")));
			data.add("userNum", count);
		}
		return page;
	}

	@Override
	public List<Model> list(Model params) {
		RbacOrgRoleDao dao=factory.getDao(RbacOrgRoleDao.class);
		return dao.queryList(params);
	}

	@Override
	public boolean add(String code, String orgId) {
		RbacOrgRoleDao dao=factory.getDao(RbacOrgRoleDao.class);
		long count=dao.count(Model.create().add("orgId", orgId).add("code", code));
		if(count>0) {
			return false;
		}else {
			Model model=Model.create().add("orgId", orgId).add("code", code).add("id", UUID.randomUUID().toString()).add("addTime", new Date());
			int result=dao.insert(model);
			return result>0?true:false;
		}
	}

	@Override
	@Transactional
	public boolean delete(String id) {
		RbacOrgRoleDao dao=factory.getDao(RbacOrgRoleDao.class);
		RbacUserRoleDao userRoleDao=factory.getDao(RbacUserRoleDao.class);
		long count=userRoleDao.count(Model.create().add("orId", id));
		if(count>0) {
			return false;
		}
		int result=dao.delete(Model.create().add("id", id));
		return result>0?true:false;
	}

	@Transactional
	@Override
	public boolean add(String [] code, String orgId) {
		List<Model> datas=list(Model.create().add("orgId", orgId));
		for (Model model : datas) {
			delete(model.getString("id"));
		}
		if(code!=null) {
			for (String c : code) {
				add(c, orgId);
			}
		}
		return true;
	}
}
